package k8s

import (
	"fmt"
	"time"

	//corev1 "k8s.io/api/core/v1"
	corev1 "k8s.io/api/core/v1"
	"strings"
)

// DeletePodRequest 删除Pod请求结构体
type DeletePodRequest struct {
	Name string `json:"name" validate:"required"` // Pod名称
}

// NewDefaultDeletePodRequest 创建默认的DeletePod请求
func NewDefaultDeletePodRequest() *DeletePodRequest {
	return &DeletePodRequest{}
}

// NewDeletePodRequest 创建DeletePod请求
func NewDeletePodRequest(name string) *DeletePodRequest {
	return &DeletePodRequest{
		Name: name,
	}
}

// ListPodRequest 列出Pod请求结构体
type ListPodRequest struct {
	LabelMap map[string]string `json:"label_map"` // 标签映射
}

// NewDefaultListPodRequest 创建默认的ListPod请求
func NewDefaultListPodRequest() *ListPodRequest {
	return &ListPodRequest{
		LabelMap: make(map[string]string),
	}
}

// AddLabel 添加标签
func (r *ListPodRequest) AddLabel(key, value string) *ListPodRequest {
	r.LabelMap[key] = value
	return r
}

// GetPodRequest 获取Pod请求结构体
type GetPodRequest struct {
	Name string `json:"name" validate:"required"` // Pod名称
}

// NewDefaultGetPodRequest 创建默认的GetPod请求
func NewDefaultGetPodRequest() *GetPodRequest {
	return &GetPodRequest{}
}

// NewGetPodRequest 创建GetPod请求
func NewGetPodRequest(name string) *GetPodRequest {
	return &GetPodRequest{
		Name: name,
	}
}

// CreatePodRequest 创建Pod请求结构体
type CreatePodRequest struct {
	PodYaml string `json:"pod_yaml" validate:"required"` // Pod YAML字符串
}

// NewDefaultCreatePodRequest 创建默认的CreatePod请求
func NewDefaultCreatePodRequest() *CreatePodRequest {
	return &CreatePodRequest{}
}

// NewCreatePodRequest 创建CreatePod请求
func NewCreatePodRequest(podYaml string) *CreatePodRequest {
	return &CreatePodRequest{
		PodYaml: podYaml,
	}
}

// ExecInPodRequest 在Pod中执行命令请求结构体
type ExecInPodRequest struct {
	PodName       string `json:"pod_name" validate:"required"`       // Pod名称
	ContainerName string `json:"container_name" validate:"required"` // 容器名称
	Cmd           string `json:"cmd" validate:"required"`            // 执行的命令
}

// NewDefaultExecInPodRequest 创建默认的ExecInPod请求
func NewDefaultExecInPodRequest() *ExecInPodRequest {
	return &ExecInPodRequest{}
}

// NewExecInPodRequest 创建ExecInPod请求
func NewExecInPodRequest(podName, containerName, cmd string) *ExecInPodRequest {
	return &ExecInPodRequest{
		PodName:       podName,
		ContainerName: containerName,
		Cmd:           cmd,
	}
}

// PatchPodRequest Patch Pod请求结构体
type PatchPodFromJsonRequest struct {
	Pod  string      `json:"pod" validate:"required"`  // Pod名称
	Data interface{} `json:"data" validate:"required"` // Patch数据
}

// NewDefaultPatchPodRequest 创建默认的PatchPod请求
func NewDefaultPatchPodFromJsonRequest() *PatchPodFromJsonRequest {
	return &PatchPodFromJsonRequest{}
}

// NewPatchPodRequest 创建PatchPod请求
func NewPatchPodFromJsonRequest(pod string, data interface{}) *PatchPodFromJsonRequest {
	return &PatchPodFromJsonRequest{
		Pod:  pod,
		Data: data,
	}
}

// PatchPodRequest Patch Pod请求结构体
type PutPodFromYamlRequest struct {
	YamlStr string `json:"yaml_str" validate:"required"` // YAML字符串
}

// NewDefaultPutPodFromYamlRequest 创建默认的PutPodFromYaml请求
func NewDefaultPutPodFromYamlRequest() *PutPodFromYamlRequest {
	return &PutPodFromYamlRequest{}
}

// NewPutPodFromYamlRequest 创建PutPodFromYaml请求
func NewPutPodFromYamlRequest(yamlStr string) *PutPodFromYamlRequest {
	return &PutPodFromYamlRequest{
		YamlStr: yamlStr,
	}
}

type GetPodStatusRequest struct {
	PodName string
}

type GetPodStatusResponse struct {
	HostIP string
	PodIP  string
	Phase  corev1.PodPhase

	Containers []ContainerStatusInfo
}

type ContainerStatusInfo struct {
	Name         string
	Ready        bool
	RestartCount int32
	Image        string
	Started      *bool

	// 完整保留
	State     *corev1.ContainerState
	LastState *corev1.ContainerState
}

func NewGetPodStatusRequest(podName string) *GetPodStatusRequest {
	return &GetPodStatusRequest{
		PodName: podName,
	}
}

func NewGetPodStatusResponse() *GetPodStatusResponse {
	return &GetPodStatusResponse{
		Containers: make([]ContainerStatusInfo, 0),
	}
}

func (r *GetPodStatusResponse) AddContainerStatus(
	name string,
	ready bool,
	restartCount int32,
	image string,
	started *bool,
	state *corev1.ContainerState,
	lastState *corev1.ContainerState,
) {
	r.Containers = append(r.Containers, ContainerStatusInfo{
		Name:         name,
		Ready:        ready,
		RestartCount: restartCount,
		Image:        image,
		Started:      started,
		State:        state,
		LastState:    lastState,
	})
}
func (c *ContainerStatusInfo) IsRunning() bool {
	return c.State != nil && c.State.Running != nil
}

func (c *ContainerStatusInfo) IsWaiting() bool {
	return c.State != nil && c.State.Waiting != nil
}

func (c *ContainerStatusInfo) IsTerminated() bool {
	return c.State != nil && c.State.Terminated != nil
}
func (c *ContainerStatusInfo) CurrentStateReason() string {
	switch {
	case c.State == nil:
		return ""
	case c.State.Running != nil:
		return "Running"
	case c.State.Waiting != nil:
		return c.State.Waiting.Reason
	case c.State.Terminated != nil:
		return c.State.Terminated.Reason
	default:
		return ""
	}
}

func nullStr(s string) string {
	if s == "" {
		return "(无)"
	}
	return s
}

func formatPodHeader(r *GetPodStatusResponse) string {
	phase := "(unknown)"
	if r.Phase != "" {
		phase = string(r.Phase)
	}

	lines := []string{
		fmt.Sprintf("Host IP   : %s", nullStr(r.HostIP)),
		fmt.Sprintf("Pod  IP   : %s", nullStr(r.PodIP)),
		fmt.Sprintf("Phase     : %s", phase),
	}

	maxLen := 0
	for _, l := range lines {
		if x := len([]rune(l)); x > maxLen {
			maxLen = x
		}
	}

	w := maxLen + 2

	var sb strings.Builder
	sb.WriteString("┌")
	sb.WriteString(strings.Repeat("─", w))
	sb.WriteString("┐\n")

	for _, l := range lines {
		padding := w - len([]rune(l))
		sb.WriteString("│ ")
		sb.WriteString(l)
		sb.WriteString(strings.Repeat(" ", padding-1))
		sb.WriteString("│\n")
	}

	sb.WriteString("└")
	sb.WriteString(strings.Repeat("─", w))
	sb.WriteString("┘\n")

	return sb.String()
}

func formatContainerState(st *corev1.ContainerState, useColor bool) string {
	if st == nil {
		return "(无)"
	}
	blue := ""
	green := ""
	yellow := ""
	red := ""
	reset := ""
	if useColor {
		blue = "\033[34m"
		green = "\033[32m"
		yellow = "\033[33m"
		red = "\033[31m"
		reset = "\033[0m"
	}

	loc := time.Now().Location()
	format := "2006-01-02 15:04:05"

	// Running 状态
	if st.Running != nil {
		t := st.Running.StartedAt.In(loc).Format(format)
		return fmt.Sprintf("%s运行中%s（启动于 %s）", green, reset, t)
	} else if st.Waiting != nil {
		reason := st.Waiting.Reason
		msg := st.Waiting.Message

		if msg != "" {
			return fmt.Sprintf("%s等待中%s（原因：%s，消息：%s）", yellow, reset, reason, msg)
		}
		return fmt.Sprintf("%s等待中%s（原因：%s）", yellow, reset, reason)
	} else if st.Terminated != nil {
		start := st.Terminated.StartedAt.In(loc).Format(format)
		end := st.Terminated.FinishedAt.In(loc).Format(format)
		reason := st.Terminated.Reason
		msg := st.Terminated.Message

		if msg != "" {
			return fmt.Sprintf(
				"%s已终止%s（退出码：%d，原因：%s，消息：%s，开始：%s，结束：%s）",
				red, reset,
				st.Terminated.ExitCode,
				reason,
				msg,
				start,
				end,
			)
		}

		return fmt.Sprintf(
			"%s已终止%s（退出码：%d，原因：%s，开始：%s，结束：%s）",
			red, reset,
			st.Terminated.ExitCode,
			reason,
			start,
			end,
		)
	}

	// 兜底
	return blue + "-" + reset
}

func (r *GetPodStatusResponse) PrettyPrint(color ...bool) string {
	useColor := false
	if len(color) > 0 && color[0] {
		useColor = true
	}

	var sb strings.Builder

	sb.WriteString(formatPodHeader(r))
	sb.WriteString("容器状态信息:\n")

	if len(r.Containers) == 0 {
		sb.WriteString("  (无容器状态)\n")
		return sb.String()
	}

	// 计算镜像最长长度用于对齐
	maxImage := 0
	for _, c := range r.Containers {
		if l := len([]rune(c.Image)); l > maxImage {
			maxImage = l
		}
	}

	for i, c := range r.Containers {
		name := c.Name
		if useColor {
			name = "\033[36m" + name + "\033[0m" // 青色
		}

		sb.WriteString(fmt.Sprintf("  容器 %d：%s\n", i+1, name))
		sb.WriteString(fmt.Sprintf("    就绪:        %v\n", c.Ready))
		sb.WriteString(fmt.Sprintf("    重启次数:    %d\n", c.RestartCount))
		sb.WriteString(fmt.Sprintf("    镜像:        %-*s\n", maxImage, c.Image))
		if c.Started != nil {
			sb.WriteString(fmt.Sprintf("    启动标记:    %v\n", *c.Started))
		} else {
			sb.WriteString("    启动标记:    (无)\n")
		}

		sb.WriteString(fmt.Sprintf("    当前状态:    %s\n", formatContainerState(c.State, useColor)))
		sb.WriteString(fmt.Sprintf("    上一次状态:  %s\n", formatContainerState(c.LastState, useColor)))
		sb.WriteString("\n")
	}

	return sb.String()
}
